<?php

namespace common\models\datas;

use Yii;
use common\components\bases\BaseModel;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use common\components\behaviors\UpdateCacheBehavior;
use common\components\extenders\MenuManage;
use common\components\helpers\Fun;

/**
 * This is the model class for table "{{%category}}".
 *
 * @property integer $id
 * @property string $name
 * @property integer $parent_id
 * @property string $arrparentid
 * @property string $arrchildid
 * @property integer $child
 * @property string $icon
 * @property integer $listorder
 * @property integer $display
 * @property string $module
 */
class Category extends \common\components\bases\BaseModel
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%category}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name'], 'required'],
            [['parent_id'], 'id_check', 'on' => ['update']],
            [['child', 'listorder', 'display', 'parent_id'], 'integer'],
            [['arrparentid', 'arrchildid', 'wechat_image', 'pc_image'], 'string'],
            [['name'], 'string', 'max' => 100],
            [['icon', 'module'], 'string', 'max' => 30]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('frontend', '自动编号'),
            'name' => Yii::t('frontend', '分类名称'),//
            'parent_id' => Yii::t('frontend', '父类'),//选择，缓存
            'arrparentid' => Yii::t('frontend', '父类数组id'),
            'arrchildid' => Yii::t('frontend', '子类数组id'),
            'child' => Yii::t('frontend', '是否存在子类'),
            'icon' => Yii::t('frontend', '图标'),
            'listorder' => Yii::t('frontend', '排序'),//
            'display' => Yii::t('frontend', '是否显示'),//
            'module' => Yii::t('frontend', '模块'),//
            'wechat_image' => Yii::t('frontend', '微信端图标'),//
            'pc_image' => Yii::t('frontend', 'pc端图标'),//
        ];
    }


    public function extraFields()
    {
        return [
            'backend_operate' => function () {

                return (new MenuManage(MenuManage::RECORD_ITEM_TOOLBAR, $this->attributes))->create();

            },
            'listorder_input' => function () {
                return Html::textInput("listorders[{$this->id}]", $this->listorder, ['size' => 2, 'class' => 'input-text']);
            },
            'category_id' => function () {
                return $this->categoryOption->category_id;
            },
            'is_show_pc' => function () {
                return $this->categoryOption->is_show_pc==1?'显示':'隐藏';
            },
            'pc_image' => function () {
                return !empty($this->categoryOption->pc_image)?'已上传':'未上传';
            },
            'is_show_wechat' => function () {
                return $this->categoryOption->is_show_wechat==1?'显示':'隐藏';
            },
            'wechat_image' => function () {
                return !empty($this->categoryOption->wechat_image)?'已上传':'未上传';
            },
            'operate'=>function(){
                return Html::a('修改',Fun::url(['/product/category/update','id'=>$this->id]));
            }
        ];
    }

    public function fields()
    {
        $fields = parent::fields();
        $fields['display'] = function () {
            switch ($this->display) {
                case 0:
                    return \Yii::t('common', '不显示');
                case 1:
                    return \Yii::t('common', '显示');
            }
        };
        return $fields;
    }


    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            [
                'class' => UpdateCacheBehavior::className(),
                'cacheName' => 'category',
                'fieldName' => 'module'
            ],
        ]);
    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        $data['Category'] = $this->attributes;
        if ($insert) {
            \Yii::$app->db->createCommand()->update("{{%category}}", ['arrchildid' => $this->id], "id={$this->id}")->execute();
            if ($this->parent_id != 0) {
                \Yii::$app->db->createCommand()->update("{{%category}}", ['child' => 1], "id={$this->parent_id}")->execute();
                $rows = Category::find()->where(['id' => $this->parent_id])->one();
                \Yii::$app->db->createCommand()->update("{{%category}}", ['arrparentid' => $rows['arrparentid'] . ',' . $this->parent_id], "id={$this->id}")->execute();
                $parentid_array = explode(',', $rows['arrparentid'] . ',' . $this->parent_id);
                foreach ($parentid_array as $v) {
                    if ($v != 0) {
                        $row = Category::find()->where(['id' => $v])->one();
                        if ($row['arrchildid'] != 0) {
                            \Yii::$app->db->createCommand()->update("{{%category}}", ['arrchildid' => $row['arrchildid'] . ',' . $this->id], "id={$v}")->execute();
                        } else {
                            \Yii::$app->db->createCommand()->update("{{%category}}", ['arrchildid' => $this->id], "id={$v}")->execute();
                        }
                    }
                }
            }
        } else {
            if (isset($changedAttributes['listorder']) && $changedAttributes['listorder'] != $this->listorder && isset($this->arrparentid)) {
                $parent = Category::find()->where(['id' => $this->parent_id])->one();
                if ($parent['parent_id'] == 0 && $this->parent_id != 0) {
                    \Yii::$app->db->createCommand()->update("{{%category}}", ['arrparentid' => '0,' . $parent['id']], "id={$this->id}")->execute();
                } elseif ($parent['parent_id'] != 0 && $this->parent_id != 0) {
                    \Yii::$app->db->createCommand()->update("{{%category}}", ['arrparentid' => $parent['arrparentid'] . ',' . $parent['id']], "id={$this->id}")->execute();
                }
                if ($this->arrchildid == 0) {
                    \Yii::$app->db->createCommand()->update("{{%category}}", ['arrchildid' => $this->id], "id={$this->id}")->execute();
                    \Yii::$app->db->createCommand()->update("{{%category}}", ['arrchildid' => $parent['arrchildid'] . ',' . $this->id], "id={$this->parent_id}")->execute();
                } else {
                    if (!strpos($parent['arrchildid'], (string)$this->id)) {
                        \Yii::$app->db->createCommand()->update("{{%category}}", ['arrchildid' => $parent['arrchildid'] . ',' . $this->id], "id={$this->parent_id}")->execute();
                    }
                }
                $child = Category::find()->where(['parent_id' => $this->id])->one();
                if ($child) {
                    \Yii::$app->db->createCommand()->update("{{%category}}", ['child' => 1], "id={$this->id}")->execute();
                } else {
                    \Yii::$app->db->createCommand()->update("{{%category}}", ['child' => 0], "id={$this->id}")->execute();
                }
            }
            if (isset($changedAttributes['parent_id']) && $changedAttributes['parent_id'] != $this->parent_id) {
                $rows = Category::find()->where(['id' => $changedAttributes['parent_id']])->one();
                if ($rows['arrchildid'] != '' && $rows['arrchildid'] != '0') {
                    $arr_arrchildid = explode(',', $rows['arrchildid']);
                    $key = array_search($this->id, $arr_arrchildid);
                    unset($arr_arrchildid[$key]);
                    $new_arrchildid = implode(',', $arr_arrchildid);
                    \Yii::$app->db->createCommand()->update("{{%category}}", ['arrchildid' => $new_arrchildid], "id={$rows['id']}")->execute();
                    $child = Category::find()->where(['parent_id' => $rows['id']])->one();
                    if (empty($child)) {
                        \Yii::$app->db->createCommand()->update("{{%category}}", ['child' => 0], "id={$rows['id']}")->execute();
                    } else {
                        \Yii::$app->db->createCommand()->update("{{%category}}", ['child' => 1], "id={$rows['id']}")->execute();
                    }
                }
                $parent = Category::find()->where(['id' => $this->parent_id])->one();
                \Yii::$app->db->createCommand()->update("{{%category}}", ['arrchildid' => $parent['arrchildid'] . ',' . $this->arrchildid, 'child' => 1], "id={$this->parent_id}")->execute();
                \Yii::$app->db->createCommand()->update("{{%category}}", ['parent_id' => $this->parent_id, 'arrparentid' => $parent['arrparentid'] . ',' . $this->parent_id], "id={$this->id}")->execute();
            }
            //arrchildid排序
        }
    }

    public function  afterDelete()
    {
        if ($this->arrparentid != "" && $this->arrparentid != '0') {
            $parentid_array = explode(',', $this->arrparentid);
            foreach ($parentid_array as $v) {
                if ($v != 0) {
                    $rows = Category::find()->where(['id' => $v])->one();
                    if ($rows['arrchildid'] != '' && $rows['arrchildid'] != '0') {
                        $arr_arrchildid = explode(',', $rows['arrchildid']);
                        $key = array_search($this->id, $arr_arrchildid);
                        unset($arr_arrchildid[$key]);
                        $new_arrchildid = implode(',', $arr_arrchildid);
                        \Yii::$app->db->createCommand()->update("{{%category}}", ['arrchildid' => $new_arrchildid], "id={$v}")->execute();
                        if ($new_arrchildid == $v) {
                            \Yii::$app->db->createCommand()->update("{{%category}}", ['child' => 0], "id={$v}")->execute();
                        }
                    }
                }
            }
        }
    }

    public function id_check($attribute)
    {
        if ($this->id == $this->parent_id) {
            $this->addError($attribute, Yii::t('frontend', '不能选择自身分类作为父类'));
        } elseif (strpos($this->arrchildid, ',') != false) {
            $this->addError($attribute, Yii::t('frontend', '无法修改存在子分类项的分类！'));
        }
    }

    /*
    *  获取该分类所有子分类id
    */
    public static function get_child_id($parent_id = 0)
    {
        global $arr;
        $category = Category::find()->where(['parent_id' => $parent_id])->asArray()->all();
        if ($category) {
            foreach ($category as $val) {
                $arr[] = $val['id'];
                self::get_child_id($val['id']);
            }
        }
        return $arr;

    }

    public function getCategoryOption()
    {
        return $this->hasOne(CategoryOption::className(), ['category_id' => 'id']);
    }

}
